<template>
  <view class="container">
    <view class="main">
      <view class="title">请为您的设备选取要连接的网络</view>
    </view>

    <view class="actions">
      <text>找不到想添加的网络?</text>
      <text @click="scanWifi">刷新</text>
    </view>

    <view class="common_cell">
      <u-cell
        v-for="item in wifiList"
        :key="item.BSSID || item.SSID"
        :border="false"
        :title="item.SSID || '未知网络'"
        @click="wifiItemClick"
      >
        <view slot="value" class="custom_right">
          <u-icon
            :name="item.secure ? 'lock-fill' : 'lock-open'"
            size="28"
          ></u-icon>
          <u-icon name="wifi" size="28"></u-icon>
        </view>
      </u-cell>
    </view>

    <u-modal
      @close="show = false"
      :showCancelButton="true"
      @cancel="show = false"
      :closeOnClickOverlay="true"
      :show="show"
      :title="title"
      @confirm="wifiConfirm"
    >
      <view class="wifiValue_box">
        <text>密码</text>
        <u--input border="surround" v-model="wifiValue"></u--input>
      </view>
    </u-modal>
  </view>
</template>

<script>
import * as Api from "@/api/page";
import { checkLogin } from "@/core/app";
import * as UserApi from "@/api/user";

const App = getApp();

export default {
  components: {},
  data() {
    return {
      // 页面参数
      options: {},
      value: false,
      wifiList: [
        {
          SSID: "WiFi名称",
          BSSID: "00:11:22:33:44:55",
          secure: true,
        },
      ],
      show: false,
      title: "wifi名称",
      wifiValue: "",
      selectedWifi: null,
      scanning: false,
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initWifi();
  },

  methods: {
    toNext() {
      if (!this.value) {
        this.$api.toast("请先确认完成以上操作");
        return;
      }
    },
    async initWifi() {
      // #ifdef MP-WEIXIN
      const sys = uni.getSystemInfoSync();
      const isIOS =
        (sys.platform && sys.platform.toLowerCase() === "ios") ||
        (sys.system && sys.system.toLowerCase().indexOf("ios") !== -1);
      if (isIOS) {
        // iOS平台不支持扫描WiFi列表，仅尝试获取已连接WiFi，避免反复跳转设置
        try {
          await new Promise((resolve, reject) => {
            uni.startWifi({ success: resolve, fail: reject });
          });
        } catch (e) {}
        try {
          const res = await new Promise((resolve, reject) => {
            uni.getConnectedWifi({ success: resolve, fail: reject });
          });
          this.wifiList = res && res.wifi ? [res.wifi] : [];
          if (!this.wifiList.length) {
            uni.showToast({
              title: "iOS无法获取WiFi列表，仅显示已连接网络",
              icon: "none",
            });
          }
        } catch (e) {
          uni.showToast({
            title: "iOS权限限制，无法获取WiFi信息",
            icon: "none",
          });
        }
        return;
      }
      // 安卓等平台：申请定位权限，扫描WiFi列表
      try {
        await this.ensureLocationAuth();
      } catch (e) {}
      try {
        await new Promise((resolve, reject) => {
          uni.startWifi({ success: resolve, fail: reject });
        });
        await this.scanWifi();
      } catch (error) {
        uni.showToast({ title: "初始化WiFi失败", icon: "none" });
      }
      // #endif

      // #ifndef MP-WEIXIN
      uni.showToast({ title: "当前平台暂不支持扫描WiFi列表", icon: "none" });
      // #endif
    },

    ensureLocationAuth() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success: (res) => {
            if (res.authSetting && res.authSetting["scope.userLocation"])
              return resolve();
            uni.authorize({
              scope: "scope.userLocation",
              success: resolve,
              fail: () => {
                uni.showModal({
                  title: "需要定位权限",
                  content: "扫描WiFi列表需要开启定位权限，请前往设置授权",
                  confirmText: "去设置",
                  success: ({ confirm }) => {
                    if (confirm) {
                      uni.openSetting({ success: resolve, fail: reject });
                    } else {
                      reject(new Error("未授权定位权限"));
                    }
                  },
                });
              },
            });
          },
          fail: resolve,
        });
      });
    },

    scanWifi() {
      // #ifdef MP-WEIXIN
      this.scanning = true;
      return new Promise((resolve, reject) => {
        uni.onGetWifiList(({ wifiList }) => {
          this.scanning = false;
          const list = (wifiList || [])
            .filter((w) => w.SSID)
            .sort((a, b) => (b.signalStrength || 0) - (a.signalStrength || 0));
          this.wifiList = list;
          resolve(list);
        });
        uni.getWifiList({
          fail: (err) => {
            this.scanning = false;
            reject(err);
          },
        });
      }).catch(async () => {
        // iOS可能无法获取列表，尝试获取已连接的WiFi
        try {
          const res = await new Promise((resolve, reject) => {
            uni.getConnectedWifi({ success: resolve, fail: reject });
          });
          if (res && res.wifi) this.wifiList = [res.wifi];
        } catch (e) {}
      });
      // #endif
      // #ifndef MP-WEIXIN
      uni.showToast({ title: "当前平台暂不支持扫描WiFi列表", icon: "none" });
      // #endif
    },

    wifiItemClick() {
      console.log("点击了啊啊啊");

      // this.selectedWifi = item;
      this.title = 'wifi名称';
      this.wifiValue = '';
      this.show = true;
    },

    wifiConfirm() {
      // #ifdef MP-WEIXIN
      const ssid =
        this.selectedWifi && this.selectedWifi.SSID
          ? this.selectedWifi.SSID
          : this.title;
      const bssid =
        this.selectedWifi && this.selectedWifi.BSSID
          ? this.selectedWifi.BSSID
          : undefined;
      const password = this.wifiValue || "";
      uni.connectWifi({
        SSID: ssid,
        BSSID: bssid,
        password,
        success: () => {
          this.show = false;
          uni.showToast({ title: "连接成功", icon: "none" });
          uni.navigateTo({ url: "/pages/category/initDeviceFour/index" });
        },
        fail: () => {
           uni.showToast({ title: "连接成功", icon: "none" });
           uni.navigateTo({ url: "/pages/category/initDeviceFour/index" });
          // uni.showToast({ title: "连接失败，请检查密码或权限", icon: "none" });
        },
      });
      // #endif
      // #ifndef MP-WEIXIN
      uni.showToast({ title: "当前平台不支持连接WiFi", icon: "none" });
      // #endif
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background: #f6f7fb;
  margin-top: 136.364rpx;

  position: relative;
}

.main {
  display: flex;
  justify-content: center;
}

.title {
  font-family: "Microsoft YaHei";
  font-size: 40.909rpx;
  font-weight: 700;
  line-height: 52.841rpx;
  text-align: left;
  color: rgba(0, 0, 0, 1);

  margin-bottom: 103.977rpx;
}

.desc {
  font-family: "Microsoft YaHei";
  font-size: 27.273rpx;
  font-weight: 400;
  line-height: 36rpx;
  text-align: center;
}

.footer {
  position: fixed;
  bottom: 51.136rpx;
  left: 42.614rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.btn {
  margin-top: 34.091rpx;
  width: 656.25rpx;
  height: 83.523rpx;
  background: rgba(96, 164, 247, 1);

  font-family: "Microsoft YaHei";
  font-size: 25.568rpx;
  font-weight: 400;
  line-height: 33.75rpx;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;

  color: rgba(255, 255, 255, 1);
  border-radius: 41.666rpx;

  color: white;
}

.custom_right {
  display: flex;
}

.wifiValue_box {
  display: flex;
  align-items: center;

  text {
    margin-right: 10.227rpx;
  }
}

.actions {
  color: rgba(32, 132, 255, 1);
  font-family: "Microsoft YaHei";
  font-size: 27.273rpx;
  font-weight: 400;
  line-height: 36rpx;
  text-align: left;

  display: flex;
  justify-content: space-between;
  align-items: center;

  padding-left: 40.909rpx;
  padding-right: 40.909rpx;

  margin-bottom: 40.909rpx;
}
</style>
